package com.xsd.xsdhouduan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xsd.xsdhouduan.common.Result;
import com.xsd.xsdhouduan.entity.Task;
import com.xsd.xsdhouduan.entity.User;
import com.xsd.xsdhouduan.entity.School;
import com.xsd.xsdhouduan.service.PlatformIncomeService;
import com.xsd.xsdhouduan.service.TaskService;
import com.xsd.xsdhouduan.service.UserService;
import com.xsd.xsdhouduan.service.SchoolService;
import com.xsd.xsdhouduan.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/api/user")
@CrossOrigin
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private TaskService taskService;
    
    @Autowired
    private SchoolService schoolService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private PlatformIncomeService platformIncomeService;
    
    /**
     * 获取用户信息
     */
    @GetMapping("/info")
    public Result<User> getUserInfo(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        try {
            String studentId = jwtUtil.getUsernameFromToken(token);
            User user = userService.getByStudentId(studentId);
            if (user != null) {
                // 获取学校名称
                if (user.getSchoolId() != null) {
                    School school = schoolService.getById(user.getSchoolId());
                    if (school != null) {
                        user.setSchoolName(school.getName());
                    }
                }
                return Result.success(user);
            } else {
                return Result.error("用户不存在");
            }
        } catch (Exception e) {
            return Result.error("获取用户信息失败");
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/info")
    public Result<String> updateUserInfo(@RequestBody User user, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            String studentId = jwtUtil.getUsernameFromToken(token);
            User currentUser = userService.getByStudentId(studentId);
            if (currentUser != null) {
                user.setId(currentUser.getId());
                user.setPassword(currentUser.getPassword()); // 保持原密码
                if (userService.updateById(user)) {
                    return Result.success("更新成功");
                }
            }
        }
        return Result.error("更新失败");
    }
    
    /**
     * 修改密码
     */
    @PutMapping("/password")
    public Result<String> updatePassword(@RequestBody Map<String, String> passwordData, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            String studentId = jwtUtil.getUsernameFromToken(token);
            User user = userService.getByStudentId(studentId);
            if (user != null) {
                String oldPassword = passwordData.get("oldPassword");
                String newPassword = passwordData.get("newPassword");
                
                // 验证旧密码
                if (userService.login(studentId, oldPassword) != null) {
                    // 更新密码
                    user.setPassword(newPassword);
                    if (userService.updateById(user)) {
                        return Result.success("密码修改成功");
                    }
                } else {
                    return Result.error("原密码错误");
                }
            }
        }
        return Result.error("修改失败");
    }
    
    /**
     * 获取已发布的任务
     */
    @GetMapping("/tasks/published")
    public Result<List<Task>> getPublishedTasks(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            String studentId = jwtUtil.getUsernameFromToken(token);
            User user = userService.getByStudentId(studentId);
            if (user != null) {
                // getByPublisherId 方法已经通过 populateTaskDetails 填充了接取者信息
                List<Task> tasks = taskService.getByPublisherId(user.getId());
                return Result.success(tasks);
            }
        }
        return Result.error("获取任务失败");
    }
    
    /**
     * 获取已接受的任务
     */
    @GetMapping("/tasks/accepted")
    public Result<List<Task>> getAcceptedTasks(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            String studentId = jwtUtil.getUsernameFromToken(token);
            User user = userService.getByStudentId(studentId);
            if (user != null) {
                List<Task> tasks = taskService.getByAccepterId(user.getId());
                return Result.success(tasks);
            }
        }
        return Result.error("获取任务失败");
    }
    
    /**
     * 获取所有任务（用户端）
     */
    @GetMapping("/tasks")
    public Result<List<Task>> getAllTasks() {
        List<Task> tasks = taskService.getAllTasksWithDetails();
        return Result.success(tasks);
    }
    
    /**
     * 发布任务
     */
    @PostMapping("/tasks")
    public Result<String> publishTask(@RequestBody Task task, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            String studentId = jwtUtil.getUsernameFromToken(token);
            User user = userService.getByStudentId(studentId);
            if (user != null) {
                // 设置发布者ID
                task.setPublisherId(user.getId());
                
                // 调用TaskService的publishTask方法，该方法已经包含了扣费和记录收入的逻辑
                if (taskService.publishTask(task)) {
                    return Result.success("发布成功");
                } else {
                    return Result.error("发布失败，可能是余额不足");
                }
            }
        }
        return Result.error("发布失败");
    }
    
    /**
     * 接受任务
     */
    @PostMapping("/tasks/{taskId}/accept")
    public Result<String> acceptTask(@PathVariable Long taskId, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            String studentId = jwtUtil.getUsernameFromToken(token);
            User user = userService.getByStudentId(studentId);
            if (user != null) {
                if (taskService.acceptTask(taskId, user.getId())) {
                    return Result.success("接受成功");
                }
            }
        }
        return Result.error("接受失败");
    }
    
    /**
     * 完成任务（由接取者完成）
     */
    @PostMapping("/tasks/{taskId}/complete")
    public Result<String> completeTask(@PathVariable Long taskId, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            String studentId = jwtUtil.getUsernameFromToken(token);
            User user = userService.getByStudentId(studentId);
            if (user != null) {
                Task task = taskService.getById(taskId);
                if (task != null && task.getAccepterId() != null && task.getAccepterId().equals(user.getId())) {
                    // 只有接取者可以完成任务
                    if (taskService.completeTask(taskId)) {
                        // 记录平台收入（完成费）- 97%的奖励给接取者
                        BigDecimal reward = task.getReward();
                        BigDecimal accepterAmount = reward.multiply(new BigDecimal("0.97"));
                        platformIncomeService.recordCompleteFee(taskId, task.getAccepterId(), accepterAmount);
                        return Result.success("任务完成，等待管理员结算");
                    }
                } else {
                    return Result.error("只有接取者可以完成任务");
                }
            }
        }
        return Result.error("完成失败");
    }
    
    
    /**
     * 取消任务（发布者取消）
     */
    @PostMapping("/tasks/{taskId}/cancel")
    public Result<String> cancelTask(@PathVariable Long taskId, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            String studentId = jwtUtil.getUsernameFromToken(token);
            User user = userService.getByStudentId(studentId);
            if (user != null) {
                Task task = taskService.getById(taskId);
                if (task != null && task.getPublisherId().equals(user.getId())) {
                    // 只有发布者可以取消任务
                    if (taskService.cancelTask(taskId)) {
                        return Result.success("取消成功");
                    }
                }
            }
        }
        return Result.error("取消失败");
    }
    
    /**
     * 放弃任务（接取者放弃）
     */
    @PostMapping("/tasks/{taskId}/abandon")
    public Result<String> abandonTask(@PathVariable Long taskId, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            String studentId = jwtUtil.getUsernameFromToken(token);
            User user = userService.getByStudentId(studentId);
            if (user != null) {
                Task task = taskService.getById(taskId);
                if (task != null && task.getAccepterId() != null && task.getAccepterId().equals(user.getId())) {
                    // 只有接取者可以放弃任务
                    if (taskService.abandonTask(taskId)) {
                        return Result.success("放弃成功");
                    }
                }
            }
        }
        return Result.error("放弃失败");
    }
    
    /**
     * 上传头像
     */
    @PostMapping("/avatar")
    public Result<Map<String, String>> uploadAvatar(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        
        try {
            String studentId = jwtUtil.getUsernameFromToken(token);
            User user = userService.getByStudentId(studentId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            if (file.isEmpty()) {
                return Result.error("请选择文件");
            }
            
            // 检查文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || !originalFilename.matches(".*\\.(jpg|jpeg|png|gif)$")) {
                return Result.error("只支持jpg、jpeg、png、gif格式的图片");
            }
            
            // 创建上传目录（使用绝对路径）
            String uploadDir = System.getProperty("user.dir") + "/uploads/avatar/";
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                boolean created = dir.mkdirs();
                System.out.println("创建目录: " + uploadDir + ", 结果: " + created);
            }
            
            // 生成唯一文件名
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = "avatar_" + user.getId() + "_" + System.currentTimeMillis() + extension;
            
            // 保存文件到服务器
            File targetFile = new File(dir, fileName);
            System.out.println("保存文件到: " + targetFile.getAbsolutePath());
            file.transferTo(targetFile);
            
            // 检查文件是否保存成功
            if (!targetFile.exists()) {
                throw new RuntimeException("文件保存失败");
            }
            System.out.println("文件保存成功，大小: " + targetFile.length() + " bytes");
            
            // 生成访问URL
            String avatarUrl = "/uploads/avatar/" + fileName;
            System.out.println("头像URL: " + avatarUrl);
            
            // 更新用户头像
            user.setAvatar(avatarUrl);
            userService.updateById(user);
            
            Map<String, String> result = new HashMap<>();
            result.put("avatar", avatarUrl);
            
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("头像上传失败: " + e.getMessage());
        }
    }
}
